
const Router = require('koa-router');
const router = new Router();
const Tool = require("./tool");

const fs = require("fs")
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'hellowaimai'
});
connection.connect();


router.get('/', (ctx, next) => {
    ctx.body = "服务器主路径"
});

//定位所在城市
router.get('/dingwei_city', async (ctx, next) => {
    let url_str = "https://elm.cangdu.org/v1/cities?type=guess"
    // console.log(url_str);
    ctx.body = await Tool.yyy(url_str)
});

//定位详细地址
router.get('/dingwei_xiangxi', async (ctx, next) => {
    let data = ctx.request.query
    let latitude = data.a
    let longitude = data.b
    let url_str = "https://elm.cangdu.org/v2/pois/" + latitude + "," + longitude + ""
    // console.log(url_str);
    ctx.body = await Tool.yyy(url_str)
});

//定位附近地址
router.get('/dingwei_fujin', async (ctx, next) => {
    let data = ctx.request.query
    let id = data.a
    let address = data.b
    address = encodeURIComponent(address)
    let url_str = "https://elm.cangdu.org/v1/pois?city_id=" + id + " &keyword=" + address + " &type=search"
    // console.log(url_str);
    ctx.body = await Tool.yyy(url_str)
});

// https://elm.cangdu.org/v1/pois?city_id=1&keyword=%E8%BF%AA%E5%A3%AB%E5%B0%BC&type=search

// 1.用户信息表 user_information
// 2.用户地址信息表 user_asset_address

// 注册接口
router.post('/register', async (ctx, next) => {
    var tel = ctx.request.body.tel
    var password = ctx.request.body.password
    var user_name = "用户" + new Date().getTime()
    var user_headimg = "http://localhost:3000/user_headimg/美团外卖.png"
    // sql 语句
    var sql_str = "select * from user_information where user_account=" + tel
    var sql_str2 = "insert into user_information (user_account , user_password, user_name, user_headimg) values ( '" + tel + "' , '" + password + "', '" + user_name + "', '" + user_headimg + "')"

    var aaa = new Promise(function (chenggong, shibai) {
        // 执行 sql 语句
        connection.query(sql_str, function (error, results, fields) {
            if (error) {
                console.log(error)
                var tmp_dic = {
                    error: 1,
                    msg: "注册失败",
                    data: []
                }
                shibai(JSON.stringify(tmp_dic))
            } else {
                if (results == "") {
                    connection.query(sql_str2, function (error, results, fields) {
                        if (error) {
                            console.log(error)
                            var tmp_dic = {
                                error: 1,
                                msg: "注册失败",
                                data: []
                            }
                            shibai(JSON.stringify(tmp_dic))
                        } else {
                            chenggong("注册成功")
                        }
                    })
                } else {
                    chenggong("该账号已注册")
                }
            }
        });
    })

    // 当前接口返回什么
    ctx.body = await aaa
});

// 密码登录接口
router.post('/login', async (ctx, next) => {
    var data = ctx.request.body
    var tel = data.tel
    var password = data.password

    var sql_str = "select * from user_information where user_account=" + tel
    var sql_str1 = `select * from user_information where user_account='` + tel + `' and user_password=` + password

    var aaa = new Promise(function (chenggong, shibai) {
        // 执行 sql 语句
        connection.query(sql_str, function (error, results, fields) {
            if (error) {
                console.log(error)
                var tmp_dic = {
                    error: 1,
                    msg: "错误",
                    data: []
                }
                shibai(JSON.stringify(tmp_dic))
            } else {
                if (results != "") {
                    // console.log(JSON.parse(JSON.stringify(results))[0].pwd)
                    connection.query(sql_str1, (error, results, fields) => {
                        if (error) {
                            console.log(error)
                            var tmp_dic = {
                                error: 1,
                                msg: "错误",
                                data: []
                            }
                            shibai(JSON.stringify(tmp_dic))
                        } else {
                            if (results != "") {
                                var tmp_dic = {
                                    error: 0,
                                    msg: "登陆成功",
                                    data: results
                                }
                                chenggong(JSON.stringify(tmp_dic))
                            } else {
                                var tmp_dic = {
                                    error: 1,
                                    msg: "密码错误",
                                    data: JSON.parse(JSON.stringify(results))
                                }
                                chenggong(JSON.stringify(tmp_dic))
                            }
                        }
                    })
                } else {
                    var tmp_dic = {
                        error: 1,
                        msg: "账号不存在",
                        data: JSON.parse(JSON.stringify(results))
                    }
                    chenggong(JSON.stringify(tmp_dic))
                }

            }
        });
    })
    // 当前接口返回什么
    ctx.body = await aaa
});

// 上传头像
router.post('/up_headimg', async (ctx, next) => {

    ctx.body = await new Promise((resolve, reject) => {
        let user_id = ctx.request.body.user_id
        let file = ctx.request.files.user_headimg
        // console.log(file)
        let file_name = new Date().getTime() + file.name
        let file_path = file.path
        let head_path = "http://localhost:3000/user_headimg/" + file_name

        let r_stream = fs.createReadStream(file_path)
        let w_stream = fs.createWriteStream("./static/user_headimg/" + file_name)
        r_stream.pipe(w_stream)
        r_stream.on("error", (err) => {
            resolve("头像上传出错", err)
        })
        w_stream.on("error", (err) => {
            resolve("头像上传出错", err)
        })

        r_stream.on("close", function () {

            let sql_str = "update user_information set user_headimg = '" + head_path + "' where user_id =" + user_id
            Tool.xxx(sql_str)
            // resolve("头像上传成功", {})
            resolve({
                msg: "头像上传成功",
                img_path: head_path
            })
        })

    })
})

// 查询修改用户信息
router.post('/update_information', async (ctx, next) => {
    var data = ctx.request.body
    var new_pwd = data.new_pwd
    let user_name = data.username
    let user_birthday = data.userbirthday
    // 查询
    let select_user_id = data.select_user_id
    // 更改用户昵称
    let update_username_id = data.update_username_id
    // 更改用户生日
    let update_birthday_id = data.update_birthday_id
    // 更改用户密码
    var update_pwd_id = data.update_pwd_id
    if (update_username_id != undefined) {
        // console.log("修改用户昵称")
        var sql_str = "update user_information set user_name = '" + user_name + "' where user_id =" + update_username_id
    } else if (update_birthday_id != undefined) {
        // console.log("修改用户生日")
        var sql_str = "update user_information set user_birthday = '" + user_birthday + "' where user_id =" + update_birthday_id
    } else if (select_user_id != undefined) {
        // console.log("查询用户信息")
        var sql_str = "select * from user_information where user_id=" + select_user_id
    } else if (update_pwd_id != undefined) {
        var sql_str = `update user_information set user_password = '` + new_pwd + `' where user_id =` + update_pwd_id
    }
    ctx.body = await Tool.xxx(sql_str)

})

// 用户收货地址
router.post('/user_asset_address', async (ctx, next) => {
    var data = ctx.request.body.content
    var name = data.name
    var tel = data.tel
    var province = data.province
    var city = data.city
    var county = data.county
    var addressdetail = data.addressDetail
    var address = addressdetail
    var user_id = ctx.request.body.user_id
    var areacode = data.areaCode
    var isdefault = data.isDefault

    var sql_str = `insert into user_asset_address (name ,
        tel, province, city, county, addressdetail, 
        user_id, areacode, isdefault, address) values ( '` + name + `' , 
         '` + tel + `' , '` + province + `' , '` + city + `' ,'`
        + county + `' , '` + addressdetail + `' , '` + user_id + `' , '`
        + areacode + `' , '` + isdefault + `', '` + address + `')`
    ctx.body = await Tool.xxx(sql_str)
})

// 获取用户收货地址
router.post('/get_user_address', async (ctx, next) => {
    var user_id = ctx.request.body.user_id
    var sql_str = "select * from user_asset_address where user_id=" + user_id
    ctx.body = await Tool.xxx(sql_str)
})

// 编辑用户地址
router.post('/user_address_edit', async (ctx, next) => {
    var data = ctx.request.body.content

    var name = data.name
    var tel = data.tel
    var province = data.province
    var city = data.city
    var county = data.county
    var addressdetail = data.addressDetail
    var address = addressdetail
    var user_id = ctx.request.body.user_id
    console.log(user_id)
    var areacode = data.areaCode
    var isdefault = data.isDefault

    var sql_str = `update user_asset_address set 
    name='`+ name + `', tel='` + tel + `', province='` + province + `',
    city='`+ city + `',county='` + county + `',addressDetail='` + addressdetail + `',
    address='`+ address + `',areaCode='` + areacode + `',isDefault='` + isdefault + `'
    where id=` + user_id

    ctx.body = await Tool.xxx(sql_str)
})


//获取全部商家 business
router.get('/get_business', async (ctx, next) => {
    let sql_str = "select * from business"
    ctx.body = await Tool.xxx(sql_str)
})


//查询商家名字
router.get('/get_business_name', async (ctx, next) => {    
    let data = ctx.request.query
    let budiness_id = data.a
    let sql_str = "select * from business where budiness_id=" + budiness_id
    ctx.body = await Tool.xxx(sql_str)
})


//根据商家名字 获取商家
router.get('/get_business_one_name', async (ctx, next) => {
    let data = ctx.request.query
    let business_name = data.a /* encodeURIComponent(data.a) */
    let sql_str = "select * from business where budiness_name=" + "\"" + business_name + "\""
    ctx.body = await Tool.xxx(sql_str)
})
//根据商家id 获取商家
router.get('/get_business_one_id', async (ctx, next) => {
    let data = ctx.request.query
    let business_id = data.business_id /* encodeURIComponent(data.a) */
    let sql_str = "select * from business where budiness_id=" + business_id
    ctx.body = await Tool.xxx(sql_str)
})


//获取某一个商家的具体信息 business
router.get('/get_business_info', async (ctx, next) => {
    let data = ctx.request.query
    let business_id = data.a
    let sql_str = "select * from food where food_suoshushangjia=" + business_id
    ctx.body = await Tool.xxx(sql_str)
    
})


//获取某商家的某一件商品的具体信息
router.get('/get_food_info', async (ctx, next) => {
    let data = ctx.request.query
    let food_id = data.a
    let sql_str = "select * from food where food_id=" + food_id
    ctx.body = await Tool.xxx(sql_str)
})

//查询用户在某商家是否有购物车
router.get('/get_user_buycar', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let budiness_id = data.b
    let sql_str = "select * from user_buycar where user_id=" + user_id + " and budiness_id=" + budiness_id
    ctx.body = await Tool.xxx(sql_str)
})

//查询某用户的所有购物车
router.get('/get_user_all_buycar', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let sql_str = "select * from user_buycar where user_id=" + user_id 
    ctx.body = await Tool.xxx(sql_str)
})



//增加购物车
router.get('/add_user_buycar', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let food_id = data.b
    let food_quantity = data.c
    let budiness_id = data.d
    let sql_str4 = "select * from food where food_suoshushangjia=" + budiness_id + " and food_id=" + food_id
    let data3 = JSON.parse(await Tool.xxx(sql_str4)).data
    let food_yuanjia = data3[0].food_yuanjia
    let food_zhekoujia = data3[0].food_zhekoujia
    let zong_yuanjia = food_yuanjia * food_quantity
    let zong_zhekoujia = food_zhekoujia * food_quantity
    let sql_str1 = "select * from user_buycar where user_id=" + user_id + " and food_id=" + food_id
    let data2 = JSON.parse(await Tool.xxx(sql_str1)).data
    if(data2.length > 0){
        let sql_str2 = "update user_buycar set food_quantity=" + food_quantity + " where user_id=" + user_id + " and food_id=" + food_id + ""
        let sql_str5 = "update user_buycar set zong_yuanjia=" + zong_yuanjia + " where user_id=" + user_id + " and food_id=" + food_id + ""
        let sql_str6 = "update user_buycar set zong_zhekoujia=" + zong_zhekoujia + " where user_id=" + user_id + " and food_id=" + food_id + ""
        ctx.body = await Tool.xxx(sql_str2)
        ctx.body = await Tool.xxx(sql_str5)
        ctx.body = await Tool.xxx(sql_str6)
    }else{
        let sql_str3 = "insert into user_buycar (user_id , food_id , budiness_id , food_quantity , food_yuanjia , food_zhekoujia , zong_yuanjia , zong_zhekoujia) values (' "+ user_id +"' , '" + food_id + "', '" + budiness_id + "' , '" + food_quantity + "' , '" + food_yuanjia + "' , '" + food_zhekoujia + "' , '" + zong_yuanjia + "' , '" + zong_zhekoujia + "')"
        ctx.body = await Tool.xxx(sql_str3)
    }
})



// 减少购物车 user_id  food_id
router.get('/reduce_user_buycar', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let food_id = data.b
    let food_quantity = data.c
    let budiness_id = data.d
    let sql_str4 = "select * from food where food_suoshushangjia=" + budiness_id + " and food_id=" + food_id
    let data3 = JSON.parse(await Tool.xxx(sql_str4)).data
    let food_yuanjia = data3[0].food_yuanjia
    let food_zhekoujia = data3[0].food_zhekoujia
    let zong_yuanjia = food_yuanjia * food_quantity
    let zong_zhekoujia = food_zhekoujia * food_quantity
    let sql_str1 = "select * from user_buycar where user_id=" + user_id + " and food_id=" + food_id
    let data2 = JSON.parse(await Tool.xxx(sql_str1)).data
    if(data2[0].food_quantity > 1){
        let sql_str2 = "update user_buycar set food_quantity=" + food_quantity + " where user_id=" + user_id + " and food_id=" + food_id + ""
        let sql_str5 = "update user_buycar set zong_yuanjia=" + zong_yuanjia + " where user_id=" + user_id + " and food_id=" + food_id + ""
        let sql_str6 = "update user_buycar set zong_zhekoujia=" + zong_zhekoujia + " where user_id=" + user_id + " and food_id=" + food_id + ""
        ctx.body = await Tool.xxx(sql_str2)
        ctx.body = await Tool.xxx(sql_str5)
        ctx.body = await Tool.xxx(sql_str6)
    }else if(data2[0].food_quantity == 1){
        let sql_str7 = "delete from user_buycar where budiness_id=" + budiness_id + " and food_id="+ food_id +""
        ctx.body = await Tool.xxx(sql_str7)
    }else{
        let sql_str3 = "insert into user_buycar (user_id , food_id , budiness_id , food_quantity , food_yuanjia , food_zhekoujia , zong_yuanjia , zong_zhekoujia) values (' "+ user_id +"' , '" + food_id + "' , '" + budiness_id + "' , '" + food_quantity + "' , '" + food_yuanjia + "' , '" + food_zhekoujia + "' , '" + zong_yuanjia + "' , '" + zong_zhekoujia + "')"
        ctx.body = await Tool.xxx(sql_str3)

    }
})


// 清空用户某商家的购物车 user_id
router.get('/clear_budiness_buycar', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let budiness_id = data.b
    let sql_str = "delete from user_buycar where user_id=" + user_id + " and budiness_id=" + budiness_id + ""
    ctx.body = await Tool.xxx(sql_str)
})

// 清空某用户所有的购物车 user_id
router.get('/clear_user_buycar', async (ctx, next) => {
    let user_id = ctx.request.query.user_id
    let sql_str = `delete from user_buycar where user_id=` + user_id
    ctx.body = await Tool.xxx(sql_str)
})

//获取用户足迹
router.get('/get_footor', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let budiness_id = data.b
    let sql_str = "select * from footor where user_id=" + user_id
    ctx.body = await Tool.xxx(sql_str)
})


//增加足迹
router.get('/add_footor', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let budiness_id = data.b
    console.log(budiness_id);
    let status = false
    let sql_str1 = "select * from footor where user_id=" + user_id
    let a = JSON.parse(await Tool.xxx(sql_str1)).data
    console.log('这是数据');
    a.map((item) => {
        if(item.budiness_id == budiness_id){
            console.log(1111111);
            console.log(item);
            status = true
        }
    })
    if(status == false){
        let sql_str2 = "insert into footor (user_id , budiness_id ) values (" + user_id + " , " + budiness_id + ")     "
        ctx.body = await Tool.xxx(sql_str2)
    }else{
        ctx.body = ""
    }
    
})

//删除某用户的所有足迹
router.get('/delete_footor', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let sql_str = "delete from footor where user_id=" + user_id 
    ctx.body = await Tool.xxx(sql_str)
})





// 增加收藏商家   user_id   budiness_id
router.post('/add_user_collect', async (ctx, next) => {
    let data = ctx.request.body
    let user_id = data.user_id
    let budiness_id = data.budiness_id
    var sql_str = `select * from user_collect where budiness_id=` + budiness_id + ` and user_id=` + user_id
    var a = JSON.parse(await Tool.xxx(sql_str)).data[0]
    // console.log(a)
    if (a != undefined) {
        if (a.budiness_id != undefined) {
            var sql_str1 = `delete from user_collect where budiness_id=` + budiness_id + ` and user_id=` + user_id
        } else {
            var sql_str1 = `insert into user_collect (budiness_id, user_id ) values (` + budiness_id + `, ` + user_id + `)`
        }
    } else {
        var sql_str1 = `insert into user_collect (budiness_id, user_id ) values (` + budiness_id + `, ` + user_id + `)`

    }

    ctx.body = await Tool.xxx(sql_str1)

})

// 增加收藏食物   user_id   food_id
router.post('/add_user_collect_food', async (ctx, next) => {
    let data = ctx.request.body
    let user_id = data.user_id
    let food_id = data.food_id
    var sql_str = `select * from user_collect where food_id=` + food_id + ` and user_id=` + user_id
    var a = JSON.parse(await Tool.xxx(sql_str)).data[0]
    if (a != undefined) {
        if (a.food_id != undefined) {
            var sql_str1 = `delete from user_collect where food_id=` + food_id + ` and user_id=` + user_id
        } else {
            var sql_str1 = `insert into user_collect (food_id, user_id ) values (` + food_id + `, ` + user_id + `)`
        }
    } else {
        var sql_str1 = `insert into user_collect (food_id, user_id ) values (` + food_id + `, ` + user_id + `)`

    }
    ctx.body = await Tool.xxx(sql_str1)
})


// 查询用户收藏 user_id
router.post('/get_user_collect', async (ctx, next) => {
    let data = ctx.request.body
    let user_id = data.user_id
    var sql_str = `select * from user_collect where user_id=` + user_id

    ctx.body = await Tool.xxx(sql_str)
})


// 清空收藏   user_id
router.post('/clear_user_collect', async (ctx, next) => {
    let user_id = ctx.request.body.user_id
    let sql_str = `delete from user_collect where user_id=` + user_id
    ctx.body = await Tool.xxx(sql_str)
})

// 获取用户收藏信息 
router.post('/get_collect_data', async (ctx, next) => {
    var user_food_id = ctx.request.body.food_id
    var user_budiness_id = ctx.request.body.budiness_id
    var food_arr = []
    var business_arr = []
    for (i = 0; i < user_food_id.length; i ++) {
        var sql_str1 = `select * from food where food_id=` + user_food_id[i]
        food_arr.push(JSON.parse(await Tool.xxx(sql_str1)).data[0])
    }
    for (i = 0; i < user_budiness_id.length; i ++) {
        var sql_str1 = `select * from business where budiness_id=` + user_budiness_id[i]
        business_arr.push(JSON.parse(await Tool.xxx(sql_str1)).data[0])
    }

    var tmp_obj = {
        food_arr: food_arr,
        business_arr: business_arr
    }

    ctx.body = tmp_obj
})

//增加用户订单
router.get('/add_user_order', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let budiness_id = data.b
    let food_id = data.c
    let food_quantity = data.d
    let zong_zhekoujia = data.e
    let sql_str = "insert into order_list (user_id , budiness_id , food_id , food_quantity , zong_zhekoujia) values (" + user_id + " , " + budiness_id + " , " + food_id + " , " + food_quantity + " , " + zong_zhekoujia + ")"
    ctx.body = await Tool.xxx(sql_str)
})

//获取用户订单列表
router.get('/get_user_order', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let sql_str = "select * from order_list where user_id=" + user_id
    ctx.body = await Tool.xxx(sql_str)
})

//获取同一个商家的订单
router.get('/get_budiness_order', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let budiness_id = data.b
    let sql_str = "select * from order_list where user_id=" + user_id + " and budiness_id=" + budiness_id
    ctx.body = await Tool.xxx(sql_str)
})


//删除用户的某个订单
// let sql_str = "delete from user_buycar where user_id=" + user_id + " and budiness_id=" + budiness_id + ""
router.get('/delete_user_orde_one', async (ctx, next) => {
    let data = ctx.request.query
    let order_id = data.a
    let sql_str = "delete * from order_list where order_id=" + order_id + " and user_id=" + user_id + ""
    ctx.body = await Tool.xxx(sql_str)
})

//删数用户所有订单
router.get('/delete_user_orde_all', async (ctx, next) => {
    let data = ctx.request.query
    let user_id = data.a
    let sql_str = "delete from order_list where user_id=" + user_id
    ctx.body = await Tool.xxx(sql_str)

})


// ---------------------------
// 后台
router.get("/get_all_user", async (ctx, next) => {
    sql_str = "select * from user_information"
    // console.log(111111111111)
    ctx.body = await Tool.xxx(sql_str)
})

// 修改用户账户信息
router.post("/update_user", async (ctx, next) =>{
    var data = ctx.request.body
    console.log(data)
    var data_gai = {}
    data.map((item) => {
        if (item.index != undefined) {
            // console.log(item)
            data_gai = item
        }
    })
    var user_name = data_gai.user_name
    var user_account = data_gai.user_account
    var user_birthday = data_gai.user_birthday
    var user_password = data_gai.user_password
    if (data_gai.user_id != undefined) {
        var user_id = data_gai.user_id
        var sql_str = `update user_information set user_name='`
        + user_name +`', user_account='`+ user_account +`', 
        user_birthday='`+ user_birthday +`', user_password='`+ user_password +`' where user_id='`+ user_id +`'`
    } else {
        var sql_str = `insert into user_information (user_name, user_account, user_birthday, user_password) values ('`+ user_name +`', '`+ user_account +`', '`+ user_birthday +`', '`+ user_password +`')`
    }
    Tool.xxx(sql_str)
    var sql_str1 = `select * from user_information`
    ctx.body = await Tool.xxx(sql_str1)

})


exports.router = router